<template>
	<view>
		<view class="pad-b-80">
			<CellInput
				v-model="customerName"
				isRequire
				label="客户名称"
				placeholder="请输入客户名称"
				labelWidth="90px"
			/>
			
			<CellInput
				v-model="contacts"
				isRequire
				label="联系人"
				placeholder="请输入联系人"
				labelWidth="90px"
				style="margin-top: 1px;"
			/>
			
			<CellInput
				v-model="address"
				isRequire
				label="维修地址"
				placeholder="请输入维修地址"
				labelWidth="90px"
				rightIcon="icon-dizhi"
				rightIconColor="#3c9cff"
				style="margin-top: 1px;"
				@handleRightIconClick="toSkipMap()"
			/>
			
			<CellInput
				v-model="mobile"
				isRequire
				label="联系电话"
				placeholder="请输入联系电话"
				labelWidth="90px"
				inputRadius="0px"
				style="margin-top: 1px;"
			/>
			
			<CellInput
				v-model="serviceTime"
				isRequire
				label="服务时间"
				placeholder="请选择服务时间"
				labelWidth="90px"
				:isReadonly="dates.isRead"
				style="margin-top: 1px;"
				@focus="handleShowSelectDate"
			/>
			
			<CellSwitch v-model="isReceive" isRequire label="是否领料" labelWidth="90px" style="margin-top: 1px;" />
			
			<view class="flex flex-wrap align-center bg-dbdcf8 mar-y-10 pad-x-15">
				<CustomRadio
					class="mar-y-5 mar-r-10"
					v-for="(item, index) in managerList"
					:groudId="1"
					:key="index"
					:iconType="'radio'"
					:label="item.RealName"
					:name="item.UserName"
					:value="item.Checked"
					:in-active-value="1"
					:active-value="0"
					@handleRadioClick="handleRadioClick"
				/>
			</view>
			
			<CellInput
				v-model="componentBarcode"
				cellInputBg="#dbdcf8"
				cellInputHeight="40px"
				label="零部件条码"
				placeholder="请输入零部件条码"
				labelWidth="90px"
				inputHeight="27px"
				rightIcon="icon-iconfontscan"
				rightIconColor="#3c9cff"
				style="margin-top: 1px;"
				@handleRightIconClick="handleComponentScan"
			/>
			
			<CellInput
				v-model="cartNum"
				isRequire
				isTitleIcon
				titleIcon="icon-gongdan"
				label="车号"
				placeholder="请输入车号"
				labelWidth="90px"
				isInputIcon
				inputIcon="icon-chezi"
				inputIconColor="#bd3124"
				rightIcon="icon-iconfontscan"
				rightIconColor="#3c9cff"
				style="margin-top: 10px;"
				@handleClickLeftIcon="findRepairHistory"
				@handleRightIconClick="handleCartNumScan"
				@handleClickInputIcon="findCartInfo"
				@input="handleEnterCartNum"
			/>
			
			<CellInput
				v-model="cartType"
				isReadonly
				label="车型"
				placeholder="这个是扫描车号带出来的禁止输入"
				labelWidth="90px"
				style="margin-top: 1px;"
			/>
			
			<CellInput
				v-model="materialDesc"
				isReadonly
				label="物料描述"
				placeholder="这个是扫描车号带出来的禁止输入"
				labelWidth="90px"
				style="margin-top: 1px;"
			/>
			
			<Cell
				title="配置信息"
				isLink
				:cellHeight="50"
				style="margin-top: 1px;"
				@handleCellClick="toConfigInfo()"
			/>
			
			<Cell
				title="关键零部件号"
				isLink
				:cellHeight="50"
				style="margin-top: 1px;"
				@handleCellClick="toComponentDetail()"
			/>
			
			<CellInput
				v-model="buyerTime"
				isReadonly
				label="购买日期"
				placeholder="这个是扫描车号带出来的禁止输入"
				labelWidth="90px"
				style="margin-top: 1px;"
			/>
			
			<CellInput
				v-model="hourPrice"
				isRequire
				label="小时计"
				placeholder="请输入小时计"
				labelWidth="90px"
				style="margin-top: 1px;"
			/>
			
			<CellInput
				v-model="laborCost"
				isRequire
				label="工时费"
				placeholder="请输入工时费"
				labelWidth="90px"
				style="margin-top: 1px;"
			/>
			
			<Cell
				title="客户评级信息"
				isLink
				:cellHeight="50"
				style="margin-top: 1px;"
				@handleCellClick="toCustomerGrade()"
			/>
			
			<!-- 现场详情 -->
			<view
				class="flex align-center justify-between pad-x-15 bg-white h-px-50"
				style="margin-top: 1px;"
				@click="toSceneDetails()"
			>
				<view class="flex flex-1 align-center">
					<view class="w-px-90 font-14">
						<text>现场详情</text>
					</view>
					
					<view
						class="flex flex-1 align-center border-rad-3"
						style="height: 40px; border: 1px #dadbde solid;"
					>
						<view
							v-if="textMsgList.length > 0"
							class="flex align-center justify-center font-10 mar-l-5 color-white"
							style="width: 28px; height: 28px; border-radius: 50%; background: #e07285;"
						>
							<text>文字</text>
						</view>
						
						<view
							v-if="pictureList.length > 0"
							class="flex align-center justify-center font-10 mar-l-5 color-white"
							style="width: 28px; height: 28px; border-radius: 50%; background: #f58b41;"
						>
							<text>图片</text>
						</view>
						
						<view
							v-if="voiceList.length > 0"
							class="flex align-center justify-center font-10 mar-l-5 color-white"
							style="width: 28px; height: 28px; border-radius: 50%; background: #2cb42e;"
						>
							<text>语音</text>
						</view>
						
						<view
							v-if="videoList.length > 0"
							class="flex align-center justify-center font-10 mar-l-5 color-white"
							style="width: 28px; height: 28px; border-radius: 50%; background: #16b58c;"
						>
							<text>视频</text>
						</view>
					</view>
				</view>
				
				<view class="mar-r-15 w-px-20"></view>
			</view>
			
			<!-- 添加故障件 -->
			<view class="mar-y-10">
				<view
					class="flex justify-between align-center h-px-40 bg-dbdcf8 font-14 pad-x-15"
				>
					<text>添加故障件</text>
					<text class="iconfont icon-tianjia" style="color: #3c9cff;" @click="openRepairClassify()"></text>
				</view>
				
				<!-- 故障件列表 -->
				<view>
					<Classify
						v-for="(item, index) in repairList"
						:ref="'classify' + index"
						:key="index"
						:index="index"
						:classifyTitle="item.classifyTitle"
						:classifyName="item.classifyName"
						:classifyData="item.list"
						:repairOrderItemId="item.RepairOrderItemId"
						:isExpand="item.isExpand"
						@handleExpand="handleExpand"
						@handleAttachment="handleAttachment"
						@handleSelectRepairType="handleSelectRepairType"
						@handleSelectSettlementType="handleSelectSettlementType"
						@handleClassifyLongpress="handleDelClassify"
					/>
				</view>
			</view>
		</view>
		
		<view
			class="pos-f bg-white flex align-center pad-x-10 shadow-type-7"
			style="left: 0; bottom: 0; right: 0; height: 60px;"
		>
			<!-- 废弃 -->
			<!-- <view class="flex-1 mar-r-10">
				<u-button type="info" @click="handleToDraft()">保存到草稿</u-button>
			</view> -->
			
			<view class="flex-1">
				<u-button type="primary" @click="submitData()">提 交</u-button>
			</view>
		</view>
		
		<!-- 服务日期控件 -->
		<u-datetime-picker
			ref="datetimePicker"
			v-model="dates.time"
			:show="dates.show"
			mode="date"
			:formatter="formatter"
			@confirm="handleSelectDate"
			@cancel="handleCloseSelectDate"
		></u-datetime-picker>
		
		<!-- 故障分类弹窗 -->
		<u-picker
			title="故障分类"
			keyName="label"
			:show="classify.show"
			:columns="classify.columns"
			:defaultIndex="classify.defaultIndex"
			@confirm="selectRepairClassify"
			@cancel="closeRepairClassify"
		></u-picker>
		
		<!-- 填写故障件信息弹窗 -->
		<FaultInfo
			ref="fault"
			@handleAddRepairInfo="handleAddRepairInfo"
		/>
		
		<!-- 维修类型选择弹窗 -->
		<u-picker
			title="选择维修类型"
			keyName="label"
			:show="weixiu.show"
			:columns="weixiu.columns"
			:defaultIndex="weixiu.defaultIndex"
			@confirm="selectRepairType"
			@cancel="closeRepairType"
		></u-picker>
		
		<!-- 结算类型选择弹窗 -->
		<u-picker
			title="选择结算类型"
			keyName="label"
			:show="jiesuan.show"
			:columns="jiesuan.columns"
			:defaultIndex="jiesuan.defaultIndex"
			@confirm="selectSettlementType"
			@cancel="closeSettlementType"
		></u-picker>
	</view>
</template>

<script>
	import Cell from '@/components/Cell/index'
	import CellInput from '@/components/CellInput/index'
	import CellSwitch from '@/components/CellSwitch/index'
	import CustomRadio from '@/components/CustomRadio/index'
	import Classify from '@/components/Repair/Classify/index'
	import FaultInfo from '@/components/Repair/FaultInfo/index'
	import Utils from '@/utils/utils'
	import Settings from '@/utils/settings'
	
	import { mapState } from 'vuex'
	import { checkLogin, getSystemDate, getSubstring, getStaticUrl } from '@/utils/lib'
	import { getRepairManagers, getCartInfo, addTask, saveToDraft, getDraftInfos, getAttachmentInfo } from '@/apis/applyTask'
	
	export default {
		components: {
			Cell,
			CellInput,
			CellSwitch,
			CustomRadio,
			Classify,
			FaultInfo
		},
		
		computed: {
			...mapState({
				token: state => state.user.token,
				longitude: state => state.user.longitude,
				latitude: state => state.user.latitude,
				textMsgList: state => state.repair.textMsgList,
				pictureList: state => state.repair.pictureList,
				voiceList: state => state.repair.voiceList,
				videoList: state => state.repair.videoList,
				repairList: state => state.repair.repairList,
				classifyList: state => state.repair.classifyList,
			}),
		},
		
		data() {
			return {
				draftInfo: null, // 草稿详情
				customerName: '', // 客户名称
				contacts: '', // 联系人
				address: '', // 维修地址
				mobile: '', // 联系电话
				serviceTime: '', // 服务时间
				isReceive: 0, // 是否领料，0 未领取，1 已领取
				managerName: '', // 维修经理
				managerList: [], // 维修经理列表
				componentBarcode: '', // 零部件条码
				cartNum: '', // 车号 010503A5908、020306J9348
				cartType: '', // 车型
				cartDesc: '', // 物料（车辆）描述
				buyerTime: '', // 购买时间
				materialDesc: '', // 物料描述
				hourPrice: '', // 小时计费
				laborCost: '', // 工时费
				repairItemIds: [], // 删除的故障件 id 集合，如果是草稿中来的数据，可能会涉及到删除
				
				// 服务日期选择控件
				dates: {
					show: false,
					time: Number(new Date()),
					isRead: false,
				},
				
				// 故障分类
				classify: {
					show: false,
					classifyId: '', // 选中后的分类id
					name: '', // 选中后的分类名称
					columns: [
						[
							{ label: '液压系统', id: 2001 },
							{ label: '传动系统', id: 2002 },
							{ label: '制动系统', id: 2003 },
							{ label: '电气系统及仪表', id: 2004 },
							{ label: '转向系统', id: 2005 },
							{ label: '冷却系统', id: 2006 },
							{ label: '外观及覆盖件', id: 2007 },
							{ label: '起重系统', id: 2008 },
							{ label: '动力系统', id: 2009 },
						]
					],
					defaultIndex: [0],
				},
				
				// 维修类型
				weixiu: {
					show: false,
					columns: [
						[
							{ label: '非三包件', id: 1 },
							{ label: '股份三包', id: 2 },
							{ label: '网点三包', id: 3 }
						]
					],
					index: null, // 当前系统分类的索引
					defaultIndex: [0],
				},
				
				// 结算类型
				jiesuan: {
					show: false,
					columns: [
						[
							{ label: '实物结算', id: 1 },
							{ label: '货币结算', id: 2 },
						]
					],
					index: null, // 当前系统分类的索引
					defaultIndex: [0],
				},
			}
		},
		
		onShow() {
			checkLogin() // 校验是否登录
			this.getScanResult() // 获取扫码结果
		},
		
		onLoad() {
			// 查询维修经理列表
			this.findRepairManagers().then(() => {
				// 查询草稿信息（废弃）
				// this.findDraftInfos()
			})
		},
		
		onUnload() {
			// 页面卸载后，重置一些状态管理中的数据
			this.$store.commit('repair/setDescInfo', { type: 1, data: [] })
			this.$store.commit('repair/setDescInfo', { type: 2, data: [] })
			this.$store.commit('repair/setDescInfo', { type: 3, data: [] })
			this.$store.commit('repair/setDescInfo', { type: 4, data: [] })
			this.$store.commit('repair/resetRepairComponent', [])
			this.$store.commit('repair/setCurrentField', '') // 这句其实不用加也行，不过为了防止意外，加上
		},
		
		methods: {
			// 获取草稿信息
			findDraftInfos() {
				let params = {
					token: this.token,
					location: this.longitude + ',' + this.latitude
				}
				
				Utils.loading('正在加载数据...')
				
				getDraftInfos(params).then(res => {
					uni.hideLoading()
					if (res.Result) {
						this.showData(res.Result) // 回显草稿数据
						this.draftInfo = res.Result // 记录一下草稿信息
					} else {
						Utils.popUpMsg('none', res.Message, 1500)
					}
				}).catch(err => {
					uni.hideLoading()
				})
			},
			
			// 回显数据
			async showData(data) {
				this.customerName = data.Customer.CName // 客户名称
				this.contacts = data.Customer.LinkMan // 联系人
				this.address = data.Customer.Address // 维修地址
				this.mobile = data.Customer.Mobile // 联系电话
				this.serviceTime = data.CreateDate // 服务时间
				this.managerName = data.RepairWorker // 维修经理
				this.cartNum = data.RepairVehicle.VehicleNumber // 车号
				this.cartType = data.RepairVehicle.VehicleType // 车型
				this.buyerTime = data.RepairVehicle.BuyDate // 购买日期
				this.hourPrice = data.RepairVehicle.UsedHour.toString() // 小时计费
				this.laborCost = data.TimeFee.toString() // 工时计费
				// this.IsPicking = data. // 是否领料
				// 物流描述
				// 配置信息
				// 关键零部件号
				// 现场详情
				let info = await this.showAttachmentInfo(data.RepairOrderId)
				
				this.$store.commit('repair/setDescInfo', { type: 1, data: info.attachmentText })
				this.$store.commit('repair/setDescInfo', { type: 2, data: info.attachmentPicture })
				this.$store.commit('repair/setDescInfo', { type: 3, data: info.attachmentVoice })
				this.$store.commit('repair/setDescInfo', { type: 4, data: info.attachmentVideo })
				
				// 回显维修经理
				if (this.managerList.length > 0) {
					if (this.managerName) {
						this.managerList.forEach(item => {
							item.Checked = 0
							if (this.managerName === item.RealName) {
								item.Checked = 1
							}
						})
					} else {
						// 如果没有维修经理，那就设置第一个为默认
						this.managerList[0].Checked = 1
					}
				}
			
				// 回显故障件列表
				this.showComponents(data.ItemList)
			},
			
			// 查询附件信息
			findAttachmentInfo(id) {
				return new Promise((resolve) => {
					let params = {
						id,
						Token: this.token,
						location: this.longitude + ',' + this.latitude,
						typeEx: 0
					}
					
					getAttachmentInfo(params).then(res => {
						resolve(res)
					}).catch(err => {
						console.log(err)
					})
				})
			},
			
			// 回显附件（类似）信息
			async showAttachmentInfo(RepairOrderItemId) {
				let attachmentInfo = await this.findAttachmentInfo(RepairOrderItemId)
				let infos = attachmentInfo.Result
				let attachmentText = []
				let attachmentPicture = []
				let attachmentVoice = []
				let attachmentVideo = []
				
				if (infos && infos.length > 0) {
					let arr1 = infos.filter(j => j.AttachmentType === 1) // 获取文本内容
					let arr2 = infos.filter(j => j.AttachmentType === 2) // 获取图片内容
					let arr3 = infos.filter(j => j.AttachmentType === 4) // 获取音频内容
					let arr4 = infos.filter(j => j.AttachmentType === 8) // 获取视频内容
					
					// 如果存在文本，那么将文本添加到列表中
					if (arr1.length > 0) {
						arr1.forEach(item => {
							attachmentText.push({
								AttachmentId: item.AttachmentId , // 行 id 添加时传 0
								AttachmentType: item.AttachmentType, // 1 文本，2 图片，4 音频，8 视频
								Description: item.Description, // 文字或服务端返回的新文件名
								OriginalFileName: item.OriginalFileName, // 原始文件名
								Size: item.Size, // 文件大小
							})
						})
					}
					
					// 如果存在图片，那么将图片数据添加到列表中
					if (arr2.length > 0) {
						arr2.forEach(item => {
							attachmentPicture.push({
								AttachmentId: item.AttachmentId , // 行 id 添加时传 0
								AttachmentType: item.AttachmentType, // 1 文本，2 图片，4 音频，8 视频
								Description: getSubstring(getStaticUrl(item.Description), '/'), // 文字或服务端返回的新文件名
								OriginalFileName: item.OriginalFileName, // 原始文件名
								Size: item.Size, // 文件大小
								url: Settings.uploadIp + '/' + getStaticUrl(item.Description), // 用来回显数据的字段
							})
						})
					}
					
					// 如果存在语音，那么将语音添加到列表中
					if (arr3.length > 0) {
						arr3.forEach((item, index) => {
							attachmentVoice.push({
								// id: index + 1, // 记录当前语音位置
								AttachmentId: item.AttachmentId , // 行 id 添加时传 0
								AttachmentType: item.AttachmentType, // 1 文本，2 图片，4 音频，8 视频
								Description: getSubstring(getStaticUrl(item.Description), '/'), // 文字或服务端返回的新文件名
								OriginalFileName: item.OriginalFileName, // 原始文件名
								Size: item.Size, // 文件大小
								isPlayAudio: false, // 是否播报语音
								url: Settings.uploadIp + '/' + getStaticUrl(item.Description), // 用来回显数据的字段
							})
						})
					}
					
					// 如果存在视频，那么将视频添加到列表中
					if (arr4.length > 0) {
						arr4.forEach((item, index) => {
							attachmentVideo.push({
								// id: index + 1, // 记录当前视频位置
								AttachmentId: item.AttachmentId , // 行 id 添加时传 0
								AttachmentType: item.AttachmentType, // 1 文本，2 图片，4 音频，8 视频
								Description: getSubstring(getStaticUrl(item.Description), '/'), // 文字或服务端返回的新文件名
								OriginalFileName: item.OriginalFileName, // 原始文件名
								Size: item.Size, // 文件大小
								url: Settings.uploadIp + '/' + getStaticUrl(item.Description), // 用来回显数据的字段
							})
						})
					}
				}
				
				return {
					attachmentText,
					attachmentPicture,
					attachmentVoice,
					attachmentVideo
				}
			},
			
			// 回显故障件列表
			showComponents(list) {
				let repairList = []
				
				list.forEach(async (item) => {
					// 回显维修类型数据
					let repairTypeName = ''
					
					if (item.RepairType !== null && item.RepairType !== '') {
						if (item.RepairType === 1) {
							repairTypeName = '非三包件'
						} else if (item.RepairType === 2) {
							repairTypeName = '股份三包'
						} else if (item.RepairType === 3) {
							repairTypeName = '网点三包'
						}
					}
					
					// 回显附件等数据信息
					let info = await this.showAttachmentInfo(item.RepairOrderItemId)
					let obj = {
						classifyTitle: '系统分类',
						classifyName: this.classifyList.filter(j => j.id == item.FaultClass)[0].label,
						isExpand: true,
						RepairOrderItemId: item.RepairOrderItemId,
						list: [
							{ label: '名称', value: item.MaterialName, prop: 'name', textMsgList: [], pictureList: [], voiceList: [], videoList: [] },
							{ label: '图件号', value: item.MaterialNum, prop: 'num', textMsgList: [], pictureList: [], voiceList: [], videoList: [] },
							{ label: '单价', value: item.Price, prop: 'unitPrice', textMsgList: [], pictureList: [], voiceList: [], videoList: [] },
							{
								label: '附件',
								value: '',
								prop: 'attachment',
								textMsgList: info.attachmentText,
								pictureList: info.attachmentPicture,
								voiceList: info.attachmentVoice,
								videoList: info.attachmentVideo,
							},
							{ label: '需求数量', value: item.PlanAmount, prop: 'demand', textMsgList: [], pictureList: [], voiceList: [], videoList: [] },
							{ label: '申请数量', value: item.ApplyAmount, prop: 'apply', textMsgList: [], pictureList: [], voiceList: [], videoList: [] },
							{ label: '单位', value: item.Unit, prop: 'unit', textMsgList: [], pictureList: [], voiceList: [], videoList: [] },
							{ label: '故障件条码', value: '', prop: 'repairNo', textMsgList: [], pictureList: [], voiceList: [], videoList: [], repairNoList: [] },
							{
								label: '维修类型',
								value: repairTypeName,
								prop: 'repairType',
								textMsgList: [],
								pictureList: [],
								voiceList: [],
								videoList: [],
								isEdit: true
							},
						]
					}
					
					// 如果维修类型是股份三包，回显对应的结算类型数据
					if (item.RepairType === 2) {
						let settlementTypeName = ''
						
						if (item.SettlementType === 1) {
							settlementTypeName = '实物结算'
						} else if (item.SettlementType === 2) {
							settlementTypeName = '货币结算'
						}
						
						obj.list.push({
							label: '结算类型',
							value: settlementTypeName,
							prop: 'settlementType',
							textMsgList: [],
							pictureList: [],
							voiceList: [],
							videoList: [],
							isEdit: true,
						})
					}
					
					repairList.push(obj)
				})
				
				// 将故障件列表添加到页面中
				this.$store.commit('repair/resetRepairComponent', repairList)
			},
			
			// 查询维修经理列表
			findRepairManagers() {
				let params = {
					location: this.longitude + ',' + this.latitude,
					token: this.token
				}
				
				return new Promise((resolve, reject) => {
					getRepairManagers(params).then(res => {
						this.managerList = res.Result
						
						if (this.managerList.length > 0) {
							let arr = this.managerList.filter(item => item.Checked === 1)
							
							// 如果存在默认维修经理，那么设置默认
							if (arr.length > 0) {
								this.managerName = arr[0].UserName
							}
						}
						
						resolve()
					}).catch((err) => {
						reject(err)
					})
				})
			},
			
			// 切换姓名的回调
			handleRadioClick(name, groudId) {
				this.managerList.forEach(item => {
					item.Checked = 0
					
					if (item.UserName === name) {
						item.Checked = 1
						this.managerName = item.UserName
					}
				})
			},
			
			// 跳转到车辆配置信息页面
			toConfigInfo() {
				uni.navigateTo({
					url: `/pages/repairManage/cartConfigInfo/cartConfigInfo?cartNum=${this.cartNum}`
				})
			},
			
			// 点击关键零部件号的回调
			toComponentDetail() {
				uni.navigateTo({
					url: `/pages/repairManage/componentDetail/componentDetail?cartNum=${this.cartNum}`
				})
			},
			
			// 点击客户评级信息的回调
			toCustomerGrade() {
				uni.navigateTo({
					url: '/pages/repairManage/customerGrade/customerGrade'
				})
			},
			
			// 点击现场详情的回调
			toSceneDetails() {
				uni.navigateTo({
					url: `/pages/desc/desc?type=1&title=故障描述&isEdit=${true}`
				})
			},
			
			// 零部件扫码
			handleComponentScan() {
				// 获取当前页面
				let pages = getCurrentPages()
				let route = '/' + pages[pages.length - 1].route
				
				uni.navigateTo({ url: `/pages/scaner/scaner?prevPageUrl=${ route }&type=1` })
			},
			
			// 零部件扫码结果处理
			handleComponentScanResult(data) {
				this.componentBarcode = data
				
				setTimeout(() => {
					// 清理扫码后的页面堆栈数据
					this.clearScanCache()
				}, 1000)
			},
			
			// 点击车号左侧图标，查询车辆维修历史
			findRepairHistory() {
				if (!this.cartNum) {
					Utils.popUpMsg('error', '车号不得为空', 1500)
					return
				}
				
				uni.navigateTo({
					url: `/pages/repairManage/repairHistory/repairHistory?cartNum=${this.cartNum}`
				})
			},
			
			// 输入车号后，将小写改为大写
			handleEnterCartNum(val) {
				this.cartNum = (val !== '' && val !== null && val !== undefined) ? val.toUpperCase() : ''
			},
			
			// 点击车号表单内图标，根据车号查询车辆信息
			findCartInfo() {
				// let cartNum = '010503A5908'
				if (!this.cartNum) {
					Utils.popUpMsg('error', '车号不得为空', 1500)
					return
				}
				
				Utils.loading('正在查询车辆信息...')
				
				this.findCartInformation(this.cartNum).then(res => {
					uni.hideLoading()
					let data = res.Result
					
					this.customerName = data.CName // 客户名称
					this.contacts = data.LinkMan // 联系人
					this.address = data.Address // 维修地址
					this.mobile = data.Mobile // 联系电话
				}).catch(err => {
					uni.hideLoading()
				})
			},
			
			// 根据车号查询车辆信息
			findCartInformation(cartNum) {
				let token = this.token
				let location = this.longitude + ',' + this.latitude
				
				return new Promise((resolve, reject) => {
					getCartInfo(cartNum, token, location).then(res => {
						resolve(res)
					}).catch(err => {
						reject(err)
					})
				})
			},
			
			// 车号扫码
			handleCartNumScan() {
				// 获取当前页面
				let pages = getCurrentPages()
				let route = '/' + pages[pages.length - 1].route
				
				uni.navigateTo({ url: `/pages/scaner/scaner?prevPageUrl=${ route }&type=2` })
			},
			
			// 车号扫码结果处理
			handleCartNumScanResult(cartNum) {
				// let FORKLIFT_NUM = '010503A5908'
				Utils.loading('数据加载中...')
				
				this.findCartInformation(cartNum).then(res => {
					uni.hideLoading()
					let data = res.Result
					this.cartNum = cartNum
					this.customerName = data.CName // 客户名称
					this.contacts = data.LinkMan // 联系人
					this.address = data.Address // 维修地址
					this.mobile = data.Mobile // 联系电话
					
					// 清理扫码后的页面堆栈数据
					this.clearScanCache()
				}).catch((err) => {
					uni.hideLoading()
					Utils.popUpMsg('error', '车辆信息获取失败' + err, 5000)
					// 清理扫码后的页面堆栈数据
					this.clearScanCache()
				})
			},
			
			// 获取扫码结果
			getScanResult() {
				// 获取当前页
				let pages = getCurrentPages()
				let currentPage = pages[pages.length - 1]
				
				// 判断扫码结果是否存在
				if (currentPage.scanResult) {
					let scanResult = JSON.parse(currentPage.scanResult)
					
					if (scanResult.code === 200) {
						if (scanResult.type === 1) {
							// 零部件扫码
							this.handleComponentScanResult(scanResult.result)
						} else if (scanResult.type === 2) {
							// 车号扫码
							this.handleCartNumScanResult(scanResult.result)
						}
					} else {
						Utils.popUpMsg('none', `扫码失败：${ scanResult.result }`)
					}
				}
			},
			
			// 清理扫码后的页面堆栈数据
			clearScanCache() {
				// 处理完成后，还要把页面堆栈删除
				let pages = getCurrentPages()
				let currentPage = pages[pages.length - 1]
				
				delete currentPage.scanResult
			},
			
			// 选择服务日期
			handleShowSelectDate() {
				this.dates.isRead = true
				this.dates.show = true
			},
			
			// 格式化日期
			formatter(type, value) {
				if (type === 'year') {
					return `${value}年`
				}
				
				if (type === 'month') {
					return `${value}月`
				}
				
				if (type === 'day') {
					return `${value}日`
				}
				
				// if (type === 'hour') {
				// 	return `${value}点`
				// }
				
				// if (type === 'minute') {
				// 	return `${value}分`
				// }
				
				return value
			},
			
			// 选择日期
			handleSelectDate() {
				setTimeout(() => {
					this.serviceTime = getSystemDate(this.dates.time, 'yyyy-MM-dd')
					this.handleCloseSelectDate()
				}, 0)
			},
			
			// 关闭选择服务日期弹窗
			handleCloseSelectDate() {
				this.dates.time = Number(new Date())
				this.dates.isRead = false
				this.dates.show = false
			},
		
			// 点击添加故障件，弹出选择故障分类弹窗
			openRepairClassify() {
				this.classify.show = true
			},
			
			// 选择故障分类
			selectRepairClassify(e) {
				this.classify.classifyId = e.value[0].id // 设置选中项的id
				this.classify.name = e.value[0].label // 设置选中项的名称
				this.closeRepairClassify() // 关闭选择故障分类弹出
				this.$refs.fault.handleOpen() // 打开填写故障件信息弹窗
			},
			
			// 关闭故障分类
			closeRepairClassify(e) {
				this.classify.defaultIndex = [0]
				this.classify.show = false
			},
			
			// 点击系统分类名称时的回调（展开/收起信息）
			handleExpand(index) {
				let repairList = JSON.parse(JSON.stringify(this.repairList))
				
				repairList.map((item, i) => {
					if (i === index) {
						item.isExpand = !item.isExpand
						
						return item
					}
				})
				
				this.$store.commit('repair/resetRepairComponent', repairList)
			},
			
			// 点击附件的回调
			handleAttachment({ index, row }) {
				uni.navigateTo({
					url: `/pages/desc/desc?type=2&title=故障描述&index=${index}&isEdit=${true}`
				})
			},
			
			// 填写完故障件信息后的回调
			handleAddRepairInfo(data) {
				let obj = {
					classifyTitle: '系统分类',
					classifyName: this.classify.name,
					isExpand: true,
					list: [
						{ label: '名称', value: data.name, prop: 'name', textMsgList: [], pictureList: [], voiceList: [], videoList: [] },
						{ label: '图件号', value: data.num, prop: 'num', textMsgList: [], pictureList: [], voiceList: [], videoList: [] },
						{ label: '单价', value: data.unitPrice, prop: 'unitPrice', textMsgList: [], pictureList: [], voiceList: [], videoList: [] },
						{ label: '附件', value: '', prop: 'attachment', textMsgList: [], pictureList: [], voiceList: [], videoList: [] },
						{ label: '需求数量', value: data.demand, prop: 'demand', textMsgList: [], pictureList: [], voiceList: [], videoList: [] },
						{ label: '申请数量', value: data.apply, prop: 'apply', textMsgList: [], pictureList: [], voiceList: [], videoList: [] },
						{ label: '单位', value: data.unit, prop: 'unit', textMsgList: [], pictureList: [], voiceList: [], videoList: [] },
						{ label: '故障件条码', value: '', prop: 'repairNo', textMsgList: [], pictureList: [], voiceList: [], videoList: [], repairNoList: [] },
						{
							label: '维修类型',
							value: '',
							prop: 'repairType',
							textMsgList: [],
							pictureList: [],
							voiceList: [],
							videoList: [],
							isEdit: true,
						},
					]
				}
				
				// 将添加的故障件信息加入到状态管理中
				this.$store.commit('repair/setRepairComponent', obj)
				
				// 清除选择故障分类的名称
				this.classify.name = ''
			},
			
			// 打开选择维修类型弹窗
			handleSelectRepairType(index) {
				this.weixiu.index = index
				this.weixiu.show = true
			},
			
			// 选择维修类型
			selectRepairType(e) {
				let name = e.value[0].label
				let list = JSON.parse(JSON.stringify(this.repairList))
				
				list.forEach((item, index) => {
					if (index === this.weixiu.index) {
						item.list.forEach(j => {
							if (j.prop === 'repairType') {
								j.value = name
							}
						})
					}
				})
				
				if (name === '股份三包') {
					list.forEach((item, index) => {
						if (index === this.weixiu.index) {
							item.list.push({
								label: '结算类型',
								value: '',
								prop: 'settlementType',
								textMsgList: [],
								pictureList: [],
								voiceList: [],
								videoList: [],
								isEdit: true,
							})
						}
					})
				} else {
					list.forEach((item, index) => {
						if (index === this.weixiu.index) {
							item.list.forEach((j, i) => {
								if (j.prop === 'settlementType') {
									item.list.splice(i)
								}
							})
						}
					})
				}
				
				this.$store.commit('repair/resetRepairComponent', list)
				this.$refs['classify' + this.weixiu.index][0].handleChangeRepairType(this.weixiu.index, name)
				this.closeRepairType()
			},
			
			// 关闭选择维修类型弹窗
			closeRepairType() {
				this.weixiu.index = null
				this.weixiu.show = false
			},
			
			// 长按某个故障件分类，提示是否删除此故障件
			handleDelClassify(index) {
				Utils.modal('提示', '是否删除此故障件？', (res) => {
					if (res.confirm) {
						let obj = this.repairList.filter((item, i) => i === index)[0]
						
						// 如果删除的故障件是从后台查询过来的，需要将删除的故障件id传给父组件
						if (obj.repairOrderItemId !== '' && obj.repairOrderItemId !== null && obj.repairOrderItemId !== undefined) {
							// 这个页面直接这么写就行了，不用和公共组件写成一样
							this.handleDelRepairComponent(obj.repairOrderItemId)
						}
						
						this.$store.commit('repair/delRepairComponent', index)
					}
				})
			},
			
			// 打开选择结算类型弹窗
			handleSelectSettlementType(index) {
				this.jiesuan.index = index
				this.jiesuan.show = true
			},
			
			// 选择结算类型
			selectSettlementType(e) {
				let name = e.value[0].label
				let list = JSON.parse(JSON.stringify(this.repairList))
				
				list.forEach((item, index) => {
					if (index === this.jiesuan.index) {
						item.list.forEach(j => {
							if (j.prop === 'settlementType') {
								j.value = name
							}
						})
					}
				})
				
				this.$store.commit('repair/resetRepairComponent', list)
				this.$refs['classify' + this.jiesuan.index][0].handleChangeRepairType(this.jiesuan.index, name)
				this.closeSettlementType()
			},
			
			// 关闭选择维修类型弹窗
			closeSettlementType() {
				this.jiesuan.index = null
				this.jiesuan.show = false
			},
			
			// 点击位置，跳转到地图页面
			toSkipMap() {
				uni.navigateTo({
					url: '/pages/mapPreview/mapPreview'
				})
			},
			
			// 删除故障件返回的数据信息
			handleDelRepairComponent(repairOrderItemId) {
				this.repairItemIds.push(repairOrderItemId)
			},
			
			// 校验参数
			checkQuerys() {
				if (!this.customerName) {
					Utils.popUpMsg('none', '客户名称不得为空！', 1000)
					return false
				}
				
				if (!this.contacts) {
					Utils.popUpMsg('none', '联系人不得为空！', 1000)
					return false
				}
				
				if (!this.address) {
					Utils.popUpMsg('none', '维修地址不得为空！', 1000)
					return false
				}
				
				if (!this.mobile) {
					Utils.popUpMsg('none', '联系电话不得为空！', 1000)
					return false
				}
				
				if (!this.serviceTime) {
					Utils.popUpMsg('none', '请选择服务时间！', 1000)
					return false
				}
				
				if (!this.cartNum) {
					Utils.popUpMsg('none', '车号不得为空！', 1000)
					return false
				}
				
				if (this.hourPrice === null || this.hourPrice === '') {
					Utils.popUpMsg('none', '小时计费不得为空！', 1000)
					return false
				}
				
				if (this.laborCost === null || this.laborCost === '') {
					Utils.popUpMsg('none', '工时计费不得为空！', 1000)
					return false
				}
				
				return true
			},
			
			// 获取提交的时的参数
			getQuerys() {
				// 获取故障件列表中的参数
				let repairList = JSON.parse(JSON.stringify(this.repairList))
				let ItemList = []
				let Auditor = this.managerList.filter(item => item.Checked === 1)[0].UserName
				
				repairList.forEach((item, index) => {
					let repairTypeName = item.list.filter(j => j.prop === 'repairType')[0].value
					let repairType = null
					let settlementType = null
					
					if (repairTypeName) {
						if (repairTypeName === '股份三包') {
							repairType = 2
						} else if (repairTypeName === '非三包件') {
							repairType = 1
						} else if (repairTypeName === '网点三包') {
							repairType = 3
						}
					}
					
					if (repairType === 2) {
						// 股份三包
						let settlementTypeName = item.list.filter(j => j.prop === 'settlementType')[0].value
						
						if (settlementTypeName) {
							if (settlementTypeName === '实物结算') {
								settlementType = 1
							} else if (settlementTypeName === '货币结算') {
								settlementType = 2
							}
						}
					}
					
					// 附件
					let attachmentList = []
					let textMsgList = item.list.filter(j => j.prop === 'attachment')[0].textMsgList
					let pictureList = item.list.filter(j => j.prop === 'attachment')[0].pictureList
					let voiceList = item.list.filter(j => j.prop === 'attachment')[0].voiceList
					let videoList = item.list.filter(j => j.prop === 'attachment')[0].videoList
					
					if (textMsgList.length > 0) {
						textMsgList.forEach((item, index) => {
							attachmentList.push({
								AttachmentId: item.AttachmentId , // 行 id 添加时传 0
								AttachmentType: item.AttachmentType, // 1 文本，2 图片，4 音频，8 视频
								Description: item.Description, // 文字或服务端返回的新文件名
								OriginalFileName: '', // 原始文件名
								Size: null, // 文件大小
								IsUpload: 1, // 固定传值
							})
						})
					}
					
					if (pictureList.length > 0) {
						pictureList.forEach((item, index) => {
							attachmentList.push({
								AttachmentId: item.AttachmentId , // 行 id 添加时传 0
								AttachmentType: item.AttachmentType, // 1 文本，2 图片，4 音频，8 视频
								Description: item.Description, // 文字或服务端返回的新文件名
								OriginalFileName: item.OriginalFileName, // 原始文件名
								Size: item.Size, // 文件大小
								IsUpload: 1, // 固定传值
							})
						})
					}
					
					if (voiceList.length > 0) {
						voiceList.forEach((item, index) => {
							attachmentList.push({
								AttachmentId: item.AttachmentId , // 行 id 添加时传 0
								AttachmentType: item.AttachmentType, // 1 文本，2 图片，4 音频，8 视频
								Description: item.Description, // 文字或服务端返回的新文件名
								OriginalFileName: item.OriginalFileName, // 原始文件名
								Size: item.Size, // 文件大小
								IsUpload: 1, // 固定传值
							})
						})
					}
					
					if (videoList.length > 0) {
						videoList.forEach((item, index) => {
							attachmentList.push({
								AttachmentId: item.AttachmentId , // 行 id 添加时传 0
								AttachmentType: item.AttachmentType, // 1 文本，2 图片，4 音频，8 视频
								Description: item.Description, // 文字或服务端返回的新文件名
								OriginalFileName: item.OriginalFileName, // 原始文件名
								Size: item.Size, // 文件大小
								IsUpload: 1, // 固定传值
							})
						})
					}
					
					// 故障件条码
					let repairNoList = item.list.filter(j => j.prop === 'repairNo')[0].repairNoList
					let traceItemList = []
					
					repairNoList.forEach(item => {
						traceItemList.push({
							OldTraceNum: item.OldTraceNum,
							NewTraceNum: item.OldTraceNum,
							MaterialTraceId: item.MaterialTraceId,
							RecordList: item.RecordList,
						})
					})
					
					// 系统分类
					let FaultClass = this.classifyList.filter(j => j.label === item.classifyName)[0].id
					let obj = {
						PlanAmount: item.list.filter(j => j.prop === 'demand')[0].value, // 需求数量
						ApplyAmount: item.list.filter(j => j.prop === 'apply')[0].value, // 申请数量
						AttachmentList: attachmentList, // 附件列表
						TraceItemList: traceItemList, // 故障件条形码列表
						FaultClass, // 未知参数，暂且将值设为 2001
						MaterialNumOfComp: '', // 公司图件号（暂时不填后期补上）
						MaterialNameOfComp: '', // 公司图件名称（暂时不填后期补上）
						MaterialNum: item.list.filter(j => j.prop === 'num')[0].value, // 网点图件号
						MaterialName: item.list.filter(j => j.prop === 'name')[0].value, // 网点图件名称
						RepairType: repairType, // 维修类型，1 非三包件、2 股份三包、3 网点三包(System.Int32)
						SettlementType: repairType === 2 ? settlementType : '', // 1实物结算、2货币结算(System.Int32)
						Unit: item.list.filter(j => j.prop === 'unit')[0].value, // 单位
						Price: item.list.filter(j => j.prop === 'unitPrice')[0].value, // 单价
					}
					
					// 如果从草稿查询到的数据，那么将以下参数传过去
					if (this.draftInfo) {
						obj.RepairorderItemId = this.draftInfo.RepairorderItemId
					}
					
					ItemList.push(obj)
				})
				
				// 现场详情
				let attachmentList = []
				
				if (this.textMsgList.length > 0) {
					this.textMsgList.forEach((item, index) => {
						attachmentList.push({
							AttachmentId: item.AttachmentId , // 行 id 添加时传 0
							AttachmentType: item.AttachmentType, // 1 文本，2 图片，4 音频，8 视频
							Description: item.Description, // 文字或服务端返回的新文件名
							OriginalFileName: '', // 原始文件名
							Size: null, // 文件大小
							IsUpload: 1, // 固定传值
						})
					})
				}
				
				if (this.pictureList.length > 0) {
					this.pictureList.forEach((item, index) => {
						attachmentList.push({
							AttachmentId: item.AttachmentId , // 行 id 添加时传 0
							AttachmentType: item.AttachmentType, // 1 文本，2 图片，4 音频，8 视频
							Description: item.Description, // 文字或服务端返回的新文件名
							OriginalFileName: item.OriginalFileName, // 原始文件名
							Size: item.Size, // 文件大小
							IsUpload: 1, // 固定传值
						})
					})
				}
				
				if (this.voiceList.length > 0) {
					this.voiceList.forEach((item, index) => {
						attachmentList.push({
							AttachmentId: item.AttachmentId , // 行 id 添加时传 0
							AttachmentType: item.AttachmentType, // 1 文本，2 图片，4 音频，8 视频
							Description: item.Description, // 文字或服务端返回的新文件名
							OriginalFileName: item.OriginalFileName, // 原始文件名
							Size: item.Size, // 文件大小
							IsUpload: 1, // 固定传值
						})
					})
				}
				
				if (this.videoList.length > 0) {
					this.videoList.forEach((item, index) => {
						attachmentList.push({
							AttachmentId: item.AttachmentId , // 行 id 添加时传 0
							AttachmentType: item.AttachmentType, // 1 文本，2 图片，4 音频，8 视频
							Description: item.Description, // 文字或服务端返回的新文件名
							OriginalFileName: item.OriginalFileName, // 原始文件名
							Size: item.Size, // 文件大小
							IsUpload: 1, // 固定传值
						})
					})
				}
				
				let params = {
					// applyType: 2, // 1 保养，2 维修
					Customer: {
						// CustomerId: 1,
						CName: this.customerName, // 客户名称
						LinkMan: this.contacts, // 联系人
						Address: this.address, // 维修地址
						Mobile: this.mobile, // 联系电话
						Longitude: this.longitude, // 经度
						Latitude: this.latitude, // 纬度
					},
					DotName: '', // 网点地址，此处只传空
					DelItemList: this.repairItemIds, // 删除的故障件 id
					Auditor, // 维修经理名字对应的 UserName
					RepairWorker: this.managerName, // 维修经理名字
					TimeFee: this.laborCost, // 工时费
					IsPicking: this.isReceive, // 是否领料：0 不领料（默认），1 领料
					AttachmentList: attachmentList, // 现场详情
					RepairVehicle: {
					    VehicleNumber: this.cartNum, // 车号
						VehicleType: this.cartType, // 车型
						VehicleDescription: this.cartDesc, // 物料（车辆）描述
						BuyDate: this.buyerTime, // 购买时间
						LinkMan: this.contacts, // 联系人
						Telephone: this.mobile, // 联系电话
						CustName: this.customerName, // 客户名称
						UsedHour: this.hourPrice, // 小时计费
					},
					ItemList,
					PlanDate: this.serviceTime, // 服务时间
					CreateDate: getSystemDate(false, 'yyyy-MM-dd'), // 当前系统日期
					AuditState: 0, // 固定传 0
					IsAttachment: 3, // 固定传 3
					State: 1, // 固定传 1
				}
				
				// 判断是否存在草稿
				if (this.draftInfo) {
					params.RepairTaskId = this.draftInfo.RepairTaskId
					params.RepairOrderId = this.draftInfo.RepairOrderId
					params.RepairTaskNum = this.draftInfo.RepairTaskNum
				}
				
				return params
			},
			
			// 提交（申请任务）
			submitData() {
				// 校验必填项
				if (!this.checkQuerys()) {
					return
				}
				
				Utils.loading('任务申请中...')
				
				addTask(this.getQuerys(), this.token, this.location).then(res => {
					uni.hideLoading()
					Utils.popUpMsg('success', '任务创建成功！', 500)
					setTimeout(() => {
						uni.navigateBack({ delta: 1 })
					}, 500)
				}).catch(err => {
					uni.hideLoading()
				})
			},
			
			// 保存到草稿
			handleToDraft() {
				Utils.loading('正在生成草稿...')
				saveToDraft(this.getQuerys(), this.token, this.location).then(res => {
					Utils.popUpMsg('success', '草稿创建成功！', 500)
					uni.hideLoading()
				}).catch(err => {
					uni.hideLoading()
				})
			}
		}
	}
</script>

<style>

</style>
